const {src, dest, series, watch} = require('gulp');
const del = require('del');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

const jdists = require('gulp-jdists');
const sass = require('gulp-sass');
sass.compiler = require('node-sass');

const rename = require('gulp-rename');
const postcss = require('gulp-postcss');
const pxtorpx = require('postcss-px2rpx');


const cssmin = require('cssnano');

const gulpIf = require('gulp-if');
const config = require('./env/bin');
const multiplier = config.DefaultWidth/config.UiWidth;
const isProd = config.prod == process.env.NODE_ENV;
function handelError(err){
    console.log(err);
}

function clean(){
    return del([config.output]);
}

function wxml(){
    return src([`${config.input}/**/*.wxml`, '!**/node_modules/**/*'])
    .pipe(dest(config.output));
}

function wxss(){
    return src([`${config.input}/**/*.{scss,wxss,css}`,  '!**/node_modules/**/*'])
    .pipe(sass().on('error', handelError))
    .pipe(postcss([
        pxtorpx({
            times: multiplier
        })
    ]))
    .pipe(gulpIf(isProd, postcss([
        cssmin()
    ])))
    .pipe(rename({extname: '.wxss'}))
    .pipe(dest(config.output));
}

function js(){
    return src([`${config.input}/**/*.js`, '!**/node_modules/**/*'])
    .pipe(babel())
    .pipe(isProd ? jdists({
        trigger: 'prod'
    }): jdists({
        trigger: 'dev'
    }))
    // .pipe(uglify())
    .pipe(dest(config.output))
}
function images(){
    return src([`${config.input}/images/**`])
    .pipe(dest(`${config.output}/images/`))
}
function json(){
    return src([`${config.input}/**/*.json`, '!**/node_modules/**/*'])
    .pipe(dest(config.output))
}
function wxs(){
    return src([`${config.input}/**/*.wxs`, '!**/node_modules/**/*'])
    .pipe(dest(config.output))
}
function moveNodeModules(){
    return src([`${config.input}/**/node_modules/**/*`])
    .pipe(dest(config.output))
}

function mvCloud(){
    return src([`server/**/cloud_functions/**/*`])
    .pipe(dest(config.output))
}
function watchCb(){
    return watch('src/**/*', {
        ignoreInitial: false
    }, series([clean, wxml, wxss, js, images, wxs, json, moveNodeModules, mvCloud]))
}

exports.mvCloud = mvCloud;
exports.watch = watchCb;
exports.js = js;
exports.wxss = wxss;
exports.wxml = wxml;
exports.clean = clean;
exports.default = series([clean, wxml, wxss, js, images, wxs, json, moveNodeModules, mvCloud]);